package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//ChartManager 客服看见的会话
type ChartManager struct {
	Id uint `json:"id" orm:"pk;auto"`
	ChartId uint //客户会话id
	ManagerUid uint //客服uid
	UnReadCnt uint //未读数量
	CreatedAt time.Time `json:"created_at" orm:"auto_now_add;type(datetime)"`
	UpdatedAt time.Time `json:"updated_at" orm:"auto_now;type(datetime)"`
	Status uint
}

func init()  {
	orm.RegisterModel(new(ChartManager))
}

//ChartManagerUnReadAdd 增加客服未读数量
func ChartManagerUnReadAdd(chartId, managerUid uint) (unReadCnt uint) {
	//查询是否存在记录，没有则删除会话中的接待员
	o := orm.NewOrm()
	chartManager := ChartManager{}
	err := o.QueryTable(ChartManager{}).Filter("chart_id", chartId).Filter("manager_uid", managerUid).Filter("status", 1).One(&chartManager)
	if err != nil && err != orm.ErrNoRows {
		panic(err)
	}

	//没有则新增
	if chartManager.Id == 0 {
		chartManager.ChartId = chartId
		chartManager.ManagerUid = managerUid
		chartManager.UnReadCnt = 1
		chartManager.Status = 1
		i, err := o.Insert(&chartManager)
		if err != nil {
			panic(err)
		}
		chartManager.Id = uint(i)
		return 1
	}

	//有则新增数量
	chartManager.UnReadCnt++
	_,err = o.Update(&chartManager)
	if err != nil {
		panic(err)
	}
	return chartManager.UnReadCnt
}

//ChartManagerAdd 接洽顾客
func ChartManagerAdd(chartId, managerUid uint) (chartManager ChartManager, err error) {
	chart := ChartGet(chartId)
	if chart.Id == 0 {
		err = fmt.Errorf("会话不存在")
		return
	}

	//修改会话的客服id
	chart.ManagerUid = managerUid
	chart.Save()

	//增加会话记录
	o := orm.NewOrm()
	chartManager = ChartManager{}
	err = o.QueryTable(ChartManager{}).Filter("chart_id", chartId).Filter("manager_uid", managerUid).Filter("status", 1).One(&chartManager)
	if err != nil && err != orm.ErrNoRows {
		panic(err)
	}
	if chartManager.Id == 0 {
		chartManager.ChartId = chartId
		chartManager.ManagerUid = managerUid
		chartManager.UnReadCnt = 1
		chartManager.Status = 1
		i, err := o.Insert(&chartManager)
		if err != nil {
			panic(err)
		}
		chartManager.Id = uint(i)
	}
	return
}

//消息已读
func ChartManagerReaded(uid, chart_id uint) {
	o := orm.NewOrm()

	chart := ChartManager{}
	o.QueryTable(ChartManager{}).Filter("manager_uid", uid).Filter("chart_id", chart_id).One(&chart)
	if chart.Id == 0 || chart.UnReadCnt == 0 {
		return
	}

	chart.UnReadCnt = 0
	o.Update(&chart)
}